package com.baidu.springcloud.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.baidu.springcloud.bean.Payment;
import com.baidu.springcloud.common.CommonResult;
import com.baidu.springcloud.service.PaymentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;

/**
 * @author ShiLei
 * @version v1.0
 * @date 2020-04-04 16:54
 */
@Slf4j
@RestController
public class CircleBreakerController {

    public static final String SERVICE_URL = "http://nacos-payment-provider";

    @Resource
    private RestTemplate restTemplate;

    @RequestMapping("/consumer/fallback/{id}")
//    @SentinelResource(value = "fallback") //fallback 没有任何配置 返回错误页面 给用户提示不友好
//    @SentinelResource(value = "fallback", fallback = "fallbackException") //配置兜底处理异常方法 只负责业务异常
//    @SentinelResource(value = "fallback", blockHandler = "blockHandler") //配置兜底处理异常方法 只负责sentinel配置规则异常
    @SentinelResource(value = "fallback", blockHandler = "blockHandler", fallback = "fallbackException")
//俩个都配置的话会优先选择blockHandler异常处理逻辑
    public CommonResult<Payment> fallback(@PathVariable Long id) {
        CommonResult<Payment> result = restTemplate.getForObject(SERVICE_URL + "/payment/" + id, CommonResult.class, id);
        if (id == 4) {
            throw new IllegalArgumentException("非法参数异常");
        } else if (result.getData() == null) {
            throw new NullPointerException("该id没对应记录");
        }
        return result;
    }

    public CommonResult fallbackException(@PathVariable Long id, Throwable e) {
        Payment payment = new Payment();
        return new CommonResult<>(444, "兜底异常内容 :" + e.getMessage(), payment);

    }

    public CommonResult blockHandler(@PathVariable Long id, BlockException e) {
        Payment payment = new Payment();
        return new CommonResult<>(555, "兜底异常内容 :" + e.getMessage(), payment);

    }

    //+++++++++++++++++  Open Feign  ++++++++++++++++++++++++++

    @Resource
    private PaymentService paymentService;

    @GetMapping("/consumer/payment/{id}")
    public CommonResult<Payment> payment(@PathVariable(value = "id") Long id) {
        return paymentService.payment(id);
    }

}
